﻿using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nature.Numerics
{
    [DebuggerDisplay("Sequence size = {SequenceSize}, Groups count = {GroupsCount}")]
    public class SequenceGroups<T> : IEnumerable<T[]>
    {
        T[] m_items;
        public SequenceGroups(T[] items)
        {
            m_items = items ?? new T[0];
        }

        public double GroupsCount
        {
            get 
            {
                return Nature.Numerics.Utilities.Factorial(m_items.Length);
            }
        }

        public int SequenceSize
        {
            get { return m_items.Length; }
        }
        #region IEnumerable<T[]> Members

        IEnumerable<T[]> GetStates()
        {
            if (m_items.Length == 1)
            {
                yield return m_items;
            }
            else if (m_items.Length == 2)
            {
                yield return m_items;
                yield return new T[] { m_items[1], m_items[0] };
            }
            else
            {
                foreach (T item in m_items)
                {
                    T[] array = new T[m_items.Length];
                    array[0] = item;
                    var subcomb = new SequenceGroups<T>(m_items.Where(i => false == i.Equals(item)).ToArray());
                    foreach (T[] sub in subcomb)
                    {
                        for (int j = 0; j < sub.Length; ++j)
                        {
                            array[j + 1] = sub[j];
                        }
                        yield return array;
                    }
                }
            }
        }

        IEnumerator<T[]> IEnumerable<T[]>.GetEnumerator()
        {
            return GetStates().GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetStates().GetEnumerator();
        }

        #endregion
    }
}
